import { useEffect, useRef, useState } from "react";
import styles from "./map.module.scss";

// 声明全局 Leaflet 类型
declare global {
  interface Window {
    L: any;
  }
}

// 修复 Leaflet 图标问题
if (typeof window !== "undefined" && window.L) {
  delete (window.L.Icon.Default.prototype as any)._getIconUrl;
  window.L.Icon.Default.mergeOptions({
    iconRetinaUrl:
      "",
    iconUrl:
      "",
    shadowUrl: "",
  });
}

export function Map() {
  console.log("🔄 Map 组件渲染开始，时间戳:", Date.now());

  const mapInstance = useRef<any | null>(null);
  const [mapInfo, setMapInfo] = useState({
    zoom: 2,
    center: { lat: 0, lng: 0 },
  });
  const [isLoaded, setIsLoaded] = useState(false);

  console.log("🔄 Map 组件状态:", {
    hasMapInstance: !!mapInstance.current,
    isLoaded,
    mapInfo,
  });

  const mapRef = useRef<HTMLDivElement>(null);

  // 地图初始化和清理
  useEffect(() => {
    console.log("📍 useEffect 执行 - 组件挂载");

    const initializeMapWhenReady = () => {
      if (!mapRef.current || typeof window === "undefined") {
        console.log("🗺️ Map ref or window not available");
        return;
      }

      // 确保 Leaflet 已经加载
      if (!window.L) {
        console.log("🗺️ Leaflet not loaded, retrying in 100ms...");
        setTimeout(initializeMapWhenReady, 100);
        return;
      }

      // 防止重复初始化
      if (mapInstance.current) {
        console.log("🗺️ Map already initialized, skipping");
        return;
      }

      console.log("🗺️ Initializing map...");
      //这个坐标使用latlng鼠标事件发生的地理坐标。
      let corner1 = window.L.latLng(39.88023, 104.09113),
        corner2 = window.L.latLng(30.75605, 112.478828),
        bounds = window.L.latLngBounds(corner1, corner2);

      try {
        // 初始化地图 - 设置合适的初始视图
        const map = window.L.map(mapRef.current, {
          center: [34.1715, 109.0359], // 北京坐标作为默认中心
          zoom: 10, // 设置合适的初始缩放级别
          minZoom: 8,
          maxZoom: 11,
          zoomControl: true,
          attributionControl: true,
          maxBounds: bounds,
        });

        console.log("🗺️ Map created:", map);

        // 本地瓦片层 - 添加更多配置选项
        const tiles = window.L.tileLayer(
          "http://localhost:8088/tiles/{z}/{x}/{y}.jpg",
          {
            tileSize: 256,
            minZoom: 8,
            maxZoom: 11,
            attribution: "Local Tiles",
            noWrap: true, // 防止瓦片在边界重复
            errorTileUrl:
              'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256"><rect width="256" height="256" fill="%23f5f5f5"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-family="Arial" font-size="20" fill="%23999">No Tile</text></svg>',
          },
        );

        tiles.addTo(map);
        mapInstance.current = map;

        console.log("🗺️ Map instance set:", mapInstance.current);

        setIsLoaded(true);

        // 监听地图移动和缩放事件
        map.on("moveend zoomend", () => {
          const center = map.getCenter();
          const zoom = map.getZoom();
          console.log("🗺️ Map moved/zoomed:", {
            center: { lat: center.lat, lng: center.lng },
            zoom: zoom,
          });
          setMapInfo({
            zoom,
            center: { lat: center.lat, lng: center.lng },
          });
        });

        map.on("click", (e: any) => {
          console.log("!!!click", e);
          console.log(e.latlng);
        });

        // 监听瓦片加载事件
        tiles.on("tileloadstart", function (e: any) {
          console.log("🔄 Tile load start:", e.tile?.src || e.coords);
        });

        tiles.on("tileload", function (e: any) {
          console.log("✅ Tile loaded successfully:", e.tile?.src || e.coords);
        });

        tiles.on("tileerror", function (e: any) {
          console.error(
            "❌ Tile load error:",
            e.tile?.src || e.coords,
            e.error,
          );
        });

        // 添加一个测试标记来验证坐标系统
        const testMarker = window.L.marker([39.9042, 116.4074])
          .addTo(map)
          .bindPopup("北京测试点 (39.9042, 116.4074)");

        console.log("🗺️ Map initialized successfully at:", Date.now());
      } catch (error) {
        console.error("🗺️ Error initializing map:", error);
      }
    };

    // 开始初始化过程
    initializeMapWhenReady();

    return () => {
      console.log("📍 useEffect 清理函数执行 - 组件即将卸载或重新渲染");
      if (mapInstance.current) {
        console.log("📍 在 useEffect 清理函数中清理地图");
        mapInstance.current.remove();
        mapInstance.current = null;
      }
    };
  }, []);

  // if (!isLoaded) {
  //     return (
  //         <div className={styles["map-container"]}>
  //             <div className={styles["map-loading"]}>加载地图中1...</div>
  //         </div>
  //     );
  // }

  // 测试不同位置的函数
  const testDifferentLocations = () => {
    if (!mapInstance.current) return;

    const locations = [
      { name: "原点", coords: [0, 0], zoom: 2 },
      { name: "北京", coords: [39.9042, 116.4074], zoom: 10 },
      { name: "上海", coords: [31.2304, 121.4737], zoom: 10 },
      { name: "纽约", coords: [40.7128, -74.006], zoom: 10 },
      { name: "伦敦", coords: [51.5074, -0.1278], zoom: 10 },
    ];

    locations.forEach((location, index) => {
      setTimeout(() => {
        console.log(`🌍 Testing location: ${location.name}`);
        if (mapInstance.current) {
          mapInstance.current.setView(
            location.coords as [number, number],
            location.zoom,
          );
        }
      }, index * 3000);
    });
  };

  return (
    <div className={styles["map-container"]}>
      {/* 测试控制面板 */}
      <div
        style={{
          padding: "10px",
          backgroundColor: "white",
          zIndex: 1000,
          position: "relative",
        }}
      >
        <button
          onClick={testDifferentLocations}
          style={{ marginRight: "10px", padding: "5px 10px" }}
        >
          测试不同位置
        </button>
        <span>
          当前缩放: {mapInfo.zoom}, 中心: ({mapInfo.center.lat.toFixed(4)},{" "}
          {mapInfo.center.lng.toFixed(4)})
        </span>
      </div>

      {/* Leaflet 地图容器 */}
      <div
        ref={mapRef}
        className={styles["leaflet-map"]}
        style={{
          border: "1px solid red",
          boxSizing: "border-box",
        }}
      />
    </div>
  );
}
